package Java.view.game.douniu;

import Java.utils.JDBC;
import Java.view.Common.GameFX;
import Java.view.game.dian21.Tool;
import domain.User;
import javafx.animation.FadeTransition;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.awt.*;
import java.io.*;
import java.net.Socket;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Objects;


public class douniuFX_lian extends Application {
    private static final int WIDTH = 830;
    private static final int HEIGHT = 600;
    private Pane root;
    //牌堆
    private static final ArrayList<Poker> pokerList = new ArrayList<>();
    private static ArrayList<String> playerPoker = new ArrayList<>();
    private static final ArrayList<Poker> userPlayerPoker = new ArrayList<>();
    private static final ArrayList<Poker> playerPoker1 = new ArrayList<>();
    private static final ArrayList<Poker> playerPoker2 = new ArrayList<>();
    //标签和输入框
    private TextField happyDouField;
    private Label happyDouLabel;
    private Label playerName;
    private Label computerName1;
    private Label computerName2;
    private Label selectLabel;
    private Label addHappyDou;
    //按钮
    private Button begin;
    private Button reset;
    private Button pay;
    private Button stop;
    private Button select;
    private Button no;
    private Button back;
    private ImageView backgroundView;
    private ImageView  ruleView;

    //玩家
    static Player userPlayer;
    static Player player1 = new Player("");
    static Player player2 = new Player("");
    private int happyDou = 300;
    //牌堆初始位置
    static Point cardPoint = new Point(357, 15);

    //服务器
    public static Socket socket;
    static {
        try {
            socket = new Socket("127.0.0.1", 8848);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static BufferedWriter writer;
    private static BufferedReader reader;


    //玩家
    public String[] players = new String[3];
    User user1 = new User(null);
    User user2 = new User(null);
    User user3 = new User(null);
    User user;


    // 获得用户信息
    public douniuFX_lian(User user) {
        this.user = user;
        userPlayer = new Player(user.getUsername());
        userPlayer.setAllHappyDou(user.getHappyDou() - 100); //初始化时扣除100欢乐豆
    }

    @Override
    public void start(Stage primaryStage) throws IOException {
        primaryStage.setTitle("斗牛联机");
        primaryStage.getIcons().add(new Image("file:src/image/dizhu.png"));
        root = new Pane();
        // 初始化组件
        initializeComponents();
        // 设置主界面大小
        primaryStage.setScene(new Scene(root, WIDTH, HEIGHT));
        primaryStage.show();

        String message = "login3#" + user.getUsername() + "#" + user.getPassword() + "$";
        socket = new Socket("127.0.0.1", 8848);
        writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        //向服务端传入玩家名字
        try {
            writer.write(message);
            writer.newLine();
            writer.flush();
        } catch (IOException e) {
            System.out.println("客户发送登录信息时出现异常");
            throw new RuntimeException(e);
        }

        //读取消息，获取玩家名
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String usernames = in.readLine();
        System.out.println(usernames);
        players = usernames.split("#");

        //读取消息，初始的四张牌
        BufferedReader in1 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String playerPokers = in1.readLine();
        System.out.println(playerPokers);

        if (playerPokers.startsWith("startGame#")) {
            playerPokers = playerPokers.substring(0, playerPokers.length() - 1);
        }
        ArrayList<String> eachPlayer = new ArrayList<>(); // 每个玩家的index和牌
        String[] eachPlayerData = playerPokers.split("\\$");
        Collections.addAll(eachPlayer, eachPlayerData);
        System.out.println(eachPlayer);
        ArrayList<String> datalist = new ArrayList<>();
        for (String playerData : eachPlayer) {
            ArrayList<String> playerCards = new ArrayList<>();
            String[] splitArray = playerData.split("#"); // 使用 # 进行分离
            Collections.addAll(playerCards, splitArray);
            // 将每个玩家的牌添加到 datalist 中
            datalist.addAll(playerCards);
            }

        System.out.println("datalist"+datalist);

        for (int j = 0; j < 3; j++) {
            if (Objects.equals(players[j], user.getUsername())) {
                switch (j) {
                    case 0://读取消息，我是第一个进入的
                        userPlayer.playerID = Integer.parseInt(datalist.get(1));
                        userPlayer.receiveCardsFromServer(datalist.get(2));
                        System.out.println(userPlayer.playerID);
                        System.out.println(userPlayer.handCards);
                        //读取消息，初始的四张牌
                        player1.playerID = Integer.parseInt(datalist.get(4));
                        player1.receiveCardsFromServer(datalist.get(5));
                        System.out.println(player1.playerID);
                        System.out.println(player1.handCards);
                        player2.playerID = Integer.parseInt(datalist.get(7));
                        player2.receiveCardsFromServer(datalist.get(8));
                        System.out.println(player2.playerID);
                        System.out.println(player2.handCards);
                        break;
                    case 1: //我是第2个进入的
                        userPlayer.playerID = Integer.parseInt(datalist.get(1));
                        userPlayer.receiveCardsFromServer(datalist.get(2));
                        System.out.println(userPlayer.playerID);
                        System.out.println(userPlayer.handCards);

                        player1.playerID = Integer.parseInt(datalist.get(4));
                        player1.receiveCardsFromServer(datalist.get(5));
                        System.out.println(player1.playerID);
                        System.out.println(player1.handCards);

                        player2.playerID = Integer.parseInt(datalist.get(7));
                        player2.receiveCardsFromServer(datalist.get(8));
                        System.out.println(player2.playerID);
                        System.out.println(player2.handCards);
                        break;
                    case 2://我是第3个进入的
                        userPlayer.playerID = Integer.parseInt(datalist.get(1));
                        userPlayer.receiveCardsFromServer(datalist.get(2));
                        System.out.println(userPlayer.playerID);
                        System.out.println(userPlayer.handCards);

                        player1.playerID = Integer.parseInt(datalist.get(4));
                        player1.receiveCardsFromServer(datalist.get(5));
                        System.out.println(player1.playerID);
                        System.out.println(player1.handCards);

                        player2.playerID = Integer.parseInt(datalist.get(7));
                        player2.receiveCardsFromServer(datalist.get(8));
                        System.out.println(player2.playerID);
                        System.out.println(player2.handCards);
                        break;
                }
                break;
            }
        }

        //初始化牌堆，洗牌
        initCard();
    }
    //初始化组件
    private void initializeComponents()  {
        //斗牛规则
        Image ruleImg = new Image("file:src/image/斗牛规则.png");
        ruleView = new ImageView(ruleImg);
        ruleView.setFitWidth(WIDTH);
        ruleView.setFitHeight(HEIGHT);
        root.getChildren().add(ruleView);

        //背景
        Image backgroundImg = new Image("file:src/image/背景1.jpg");
        backgroundView = new ImageView(backgroundImg);
        backgroundView.setFitWidth(WIDTH);
        backgroundView.setFitHeight(HEIGHT);
        backgroundView.setVisible(false); // 初始时隐藏背景图片
        root.getChildren().add(backgroundView);

        //开始按钮
        begin = createButton("file:src/image/game/开始游戏.png", 340, 470);
        begin.setOnAction(event -> startGame());
        //重置按钮
        reset = createButton("file:src/image/game/重新开始.png", 340, 250);
        reset.setVisible(false);
        reset.setOnAction(event -> goBack());
        //加注按钮
        pay = createButton("file:src/image/game/加注按钮.png", 635, 520);
        pay.setVisible(false);
        pay.setOnAction(event -> {
            try {
                addBet();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });
        //停止加注按钮
        stop = createButton("file:src/image/game/停止加注按钮.png", 500, 520);
        stop.setVisible(false);
        stop.setOnAction(event -> stopBetting());
        //选择牌型按钮
        select = createButton("file:src/image/game/确定按钮.png", 500, 520);
        select.setVisible(false);
        select.setOnAction(event -> {
            try {
                calculate();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });
        //没牛按钮
        no = createButton("file:src/image/game/没牛按钮.png", 635, 520);
        no.setVisible(false);
        no.setOnAction(event -> {
            try {
                noCow();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });
        //返回按钮
        back = createButton("file:src/image/返回.png", 20, 20);
        back.setOnAction(event -> goBack());
        //输入赌注框
        happyDouField = new TextField();
        happyDouField.setFont(Font.font("宋体", 16));
        happyDouField.setPromptText("请输入加注的欢乐豆数量");
        happyDouField.setPrefWidth(200);
        happyDouField.setPrefHeight(40);
        happyDouField.setLayoutX(530);
        happyDouField.setLayoutY(470);
        happyDouField.setVisible(false);
        //赌注池标签
        happyDouLabel = new Label("赌注池:" + happyDou);
        happyDouLabel.setLayoutX(550);
        happyDouLabel.setLayoutY(50);
        happyDouLabel.setFont(Font.font("黑体", 20));
        happyDouLabel.setTextFill(Color.YELLOW);
        happyDouLabel.setVisible(false);
        //赌注池添加
        addHappyDou = new Label();
        addHappyDou.setLayoutX(670);
        addHappyDou.setLayoutY(45);
        addHappyDou.setFont(Font.font("黑体", 25));
        addHappyDou.setTextFill(Color.YELLOW);
        addHappyDou.setVisible(false);
        //玩家名字标签
        playerName = new Label("");
        playerName.setFont(Font.font("宋体", 19));
        playerName.setTextFill(Color.BLACK);
        playerName.setLayoutX(140);
        playerName.setLayoutY(385);
        playerName.setVisible(false);
        //电脑1名字标签
        computerName1 = new Label("");
        computerName1.setFont(Font.font("宋体", 19));
        computerName1.setTextFill(Color.BLACK);
        computerName1.setLayoutX(140);
        computerName1.setLayoutY(170);
        computerName1.setVisible(false);
        //电脑2名字标签
        computerName2 = new Label("");
        computerName2.setFont(Font.font("宋体", 19));
        computerName2.setTextFill(Color.BLACK);
        computerName2.setLayoutX(600);
        computerName2.setLayoutY(170);
        computerName2.setVisible(false);
        //选择提示
        selectLabel = new Label("请选择加起来为整十数的三张牌");
        selectLabel.setFont(Font.font("宋体", 15));
        selectLabel.setTextFill(Color.BLACK);
        selectLabel.setLayoutX(515);
        selectLabel.setLayoutY(470);
        selectLabel.setVisible(false);

        //添加组件到主界面
        root.getChildren().addAll(begin, reset, pay, stop, happyDouField,
                happyDouLabel, playerName, computerName1, computerName2,
                selectLabel, select, no, addHappyDou, back);
    }
    //按钮样式
    private Button createButton(String imagePath, int x, int y) {
        Button button = new Button("");
        Image image = new Image(imagePath);
        ImageView imageView = new ImageView(image);
        button.setGraphic(imageView);
        button.setLayoutX(x);
        button.setLayoutY(y);
        button.setStyle("-fx-background-color: transparent; -fx-border-width: 0;");
        return button;
    }
    //返回
    private void goBack() {
        new douniuTeamFX(user).start(new Stage());
        ((Stage) back.getScene().getWindow()).close();
    }
    //初始化牌
    //准备牌，洗牌，发牌
    private void initCard() {
        //初始化牌堆
        for (int i = 0; i <= 51; i++) {
            String name = String.valueOf(i);
            Poker poker = new Poker(name, i, false);
            //牌堆的初始位置
            poker.setTranslateX(357);
            poker.setTranslateY(15);
            pokerList.add(poker);
            root.getChildren().add(poker); // 添加到场景图中
        }
        //洗牌
//        Collections.shuffle(pokerList);
    }
    //点击开始游戏
    private void startGame() {
        //移除规则介绍
        if (root != null && ruleView != null && backgroundView != null) {
            root.getChildren().remove(ruleView);
            backgroundView.setVisible(true);
        } else {
            System.out.println("组件未正确初始化！");
        }
        // 显示room发的牌
        for (int i = 0; i < 3; i++) {
            getPoker(i);
        }
        //显示加注组件
        happyDouField.setVisible(true);
        pay.setVisible(true);
        stop.setVisible(true);
        happyDouLabel.setVisible(true);
        //显示玩家名
        playerName.setText(userPlayer.getName());
        computerName1.setText(player1.getName());
        computerName2.setText(player2.getName());
        playerName.setVisible(true);
        computerName1.setVisible(true);
        computerName2.setVisible(true);
        //隐藏开始按钮
        begin.setVisible(false);

        new Thread(this::getAddBet).start();
        new Thread(this::getStopBet).start();
        new Thread(this::getScore).start();
    }

    //发牌
    private void getPoker(int i) {
        if (i % 3 == 0) { //发玩家1的牌
            playerPoker = player1.getHandCards();
            for (int j=0;j<playerPoker.size();j++)
            {
                int index = Integer.parseInt( playerPoker.get(j) );
                Poker poker = pokerList.get(index);
                playerPoker1.add(poker); //玩家1牌
                if(j == playerPoker.size()-1){
                    poker.setVisible(false);
                }
                PokerController.move(poker, cardPoint, new Point(30 + 45 * (playerPoker1.size() - 1), 205));
                poker.toFront();

            }
        }
        else if (i % 3 == 1) {//发用户自己的牌
            playerPoker = userPlayer.getHandCards();
            for (int j=0;j<playerPoker.size();j++)
            {
                int index = Integer.parseInt( playerPoker.get(j) );
                Poker poker = pokerList.get(index);
                userPlayerPoker.add(poker); //我的牌
                if(j == playerPoker.size()-1){
                    poker.setVisible(false);
                }
                PokerController.move(poker, cardPoint, new Point(200 + 45 * (userPlayerPoker.size() - 1), 415));
                poker.setCanClick(true);
                poker.turnFront();
                poker.toFront();
            }
        }
        else { //发玩家2的牌
            playerPoker = player2.getHandCards();
            for (int j=0;j<playerPoker.size();j++)
            {
                int index = Integer.parseInt( playerPoker.get(j) );
                Poker poker = pokerList.get(index);
                playerPoker2.add(poker); //玩家2牌
                if(j == playerPoker.size()-1){
                    poker.setVisible(false);
                }
                PokerController.move(poker, cardPoint, new Point(500 + 45 * (playerPoker2.size() - 1), 205));
                poker.toFront();
            }
        }
    }
    //玩家加注，并发消息告知别人
    private void addBet() throws SQLException {
        System.out.println("玩家加注");
        int allHappyDou = userPlayer.getAllHappyDou();
        int temp = Integer.parseInt(happyDouField.getText());
        if( temp < 0){
            showAlert(Alert.AlertType.ERROR, "错误", null, "欢乐豆不能为负，请输入正整数！");
        }
        else if (allHappyDou < temp){
            showAlert(Alert.AlertType.ERROR, "错误", null, "欢乐豆不足！");
        }
        else {
            allHappyDou -= temp;
            user.setHappyDou(user.getHappyDou()+temp);
            Connection connection= JDBC.getConnection();
            Statement statement=connection.createStatement();
            String sql1="UPDATE user SET happyDou ='"+user.getHappyDou()+"'WHERE username = '"+ user.getUsername() + "'";
            statement.executeUpdate(sql1);
            userPlayer.setAllHappyDou(allHappyDou);
            userPlayer.setBetHappyDou(temp);

            //发消息
            userPlayer.sendDataToServer("addBet#"+temp+ "$");
            System.out.println("addBet#"+temp+"$");
        }
    }
    //接收别人加注的消息
    private void getAddBet() {
        while(true) {
            try {
                BufferedReader in2 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String e = null;
                while (e == null|| e.isEmpty()) {
                    e = in2.readLine();
                    if (e == null || e.isEmpty()) {// 如果 e 是空字符串或者 null，跳过此次处理
                        continue;
                    }
                    if (e.startsWith("addBet#")) {
                        e = e.substring(0, e.length()-1);
                        String finalE = e;
                        Platform.runLater(() -> {
                            System.out.println("addBet#"+finalE);
                            ArrayList<String> datalist1 = new ArrayList<>();
                            String[] splitArray = finalE.split("#");
                            Collections.addAll(datalist1, splitArray);
                            System.out.println(datalist1);
                            int tempHappyDou = Integer.parseInt(datalist1.get(1));
                            happyDou += tempHappyDou;
                            happyDouLabel.setText("赌注池:" + happyDou);
                            addHappyDou.setText("+" + tempHappyDou);
                            happyDouField.setText(null);
                            addHappyDou.setVisible(true);
                            // 创建并启动FadeTransition来渐渐消失
                            FadeTransition fadeOut = new FadeTransition(Duration.seconds(2), addHappyDou);
                            fadeOut.setFromValue(1.0); // 从完全可见
                            fadeOut.setToValue(0.0); // 渐渐消失
                            fadeOut.setOnFinished(fadeEvent -> addHappyDou.setVisible(false)); //动画完成后隐藏
                            fadeOut.play();
                        });
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    //玩家停止加注
    private void stopBetting() {
        System.out.println("玩家停止加注");
        //隐藏
        happyDouField.setVisible(false);
        pay.setVisible(false);
        stop.setVisible(false);
        //显示
        selectLabel.setVisible(true);
        select.setVisible(true);
        no.setVisible(true);
        //设置玩家停牌
        userPlayer.setStop(true);
        //发消息
        userPlayer.sendDataToServer("stopBet#"+userPlayer.playerID+"$");
        System.out.println("stopBet#"+userPlayer.playerID+"$");
    }
    //三个玩家均停注
    private void getStopBet() {
        while (true){
            try {
                BufferedReader in3 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String e = null;
                while (e == null || e.isEmpty()) {
                    e = in3.readLine();
                    if (e == null || e.isEmpty()) {// 如果 e 是空字符串或者 null，跳过此次处理
                        continue;
                    }
                    if (e.startsWith("stopBet#")) {
                        System.out.println("stopBet#  " + e);
                        //发牌
                        deal();
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    //发第五张牌
    public static void deal() {
        for (int i = 0; i < 3; i++) {
            getPoker5(i);
        }
    }
    //发最后一张牌
    private static void getPoker5(int i) {
        if (i % 3 == 0) { //发玩家1的牌
            playerPoker = player1.getHandCards();
            int index = Integer.parseInt( playerPoker.get(4) );
            Poker poker = pokerList.get(index);
            System.out.println("getPoker5,player1:"+index);
            poker.setVisible(true);
        }
        else if (i % 3 == 1) {//发用户自己的牌
            playerPoker = userPlayer.getHandCards();
            int index = Integer.parseInt( playerPoker.get(4) );
            Poker poker = pokerList.get(index);
            System.out.println("getPoker5,player2:"+index);
            poker.setVisible(true);
        }
        else { //发玩家2的牌
            playerPoker = player2.getHandCards();
            int index = Integer.parseInt( playerPoker.get(4) );
            Poker poker = pokerList.get(index);
            System.out.println("getPoker5,player3"+index);
            poker.setVisible(true);
        }
    }
    //点击确定结束游戏
    private void calculate() throws SQLException {
        int sum = 0; // 选中的牌的点数之和
        int score = 0; // 剩下的的牌点数之和
        int flag = 0; //判断是不是3张牌
        //算出选中的牌的点数之和
        for (Poker tempPoker : userPlayerPoker) {
            if (tempPoker.isClicked()) {
                flag++;
                sum += Math.min(tempPoker.getValue(), 10);
            }
        }
        //算出剩下的牌点数之和
        if (sum % 10 == 0 && flag == 3){
            for (Poker tempPoker : userPlayerPoker) {
                if (!tempPoker.isClicked()) {
                    score += Math.min(tempPoker.getValue(), 10);
                }
            }
            userPlayer.setScore(score); // 设置玩家得分
            userPlayer.sendDataToServer("score#"+userPlayer.playerID+"#"+score+ "$");
            showAlert(Alert.AlertType.INFORMATION, "消息", null, "提交成功！");

            //自动计算电脑最佳得分
//            autoCalculate();
            //显示牛数
//            showEnd();
            //结算输赢
//            win();
//            reset.setVisible(true);
        }
        else if(flag !=3){
            showAlert(Alert.AlertType.INFORMATION, "消息", null, "请选择3张牌！");
        }
        else { //点数不为10
            //自动计算
            PokerController.autoCalculateBestScore(userPlayer, userPlayerPoker);
            if(userPlayer.getScore() == 0){
                System.out.println("玩家没牛");
                showAlert(Alert.AlertType.INFORMATION, "消息", null, "提交成功！");
                userPlayer.sendDataToServer("score#"+userPlayer.playerID+"#"+userPlayer.getScore()+ "$");

//                // 自动计算电脑最佳得分
//                autoCalculate();

            }else {
                showAlert(Alert.AlertType.INFORMATION, "消息", null, "请重新选择");
            }
        }
    }
    //获得所有人的分数
    private void getScore() {
        while (true){
            try {
                BufferedReader in4 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String e = null;
                while (e == null || e.isEmpty()) {
                    e = in4.readLine();
                    if (e == null || e.isEmpty()) {// 如果 e 是空字符串或者 null，跳过此次处理
                        continue;
                    }
                    if (e.startsWith("score#")) {
                        e = e.substring(0, e.length()-1);
                        String finalE = e;
                        Platform.runLater(() -> {
                            System.out.println("score#  "+finalE);
                            ArrayList<String> datalist3 = new ArrayList<>();
                            String[] splitArray = finalE.split("#");
                            Collections.addAll(datalist3, splitArray);
                            System.out.println(datalist3);
                            if(datalist3.get(1).equals("1")){
                                userPlayer.setScore(Integer.parseInt(datalist3.get(3)));
                                player1.setScore(Integer.parseInt(datalist3.get(5)));
                                player2.setScore(Integer.parseInt(datalist3.get(7)));
                            } else if (datalist3.get(1).equals("2")) {
                                userPlayer.setScore(Integer.parseInt(datalist3.get(5)));
                                player1.setScore(Integer.parseInt(datalist3.get(7)));
                                player2.setScore(Integer.parseInt(datalist3.get(3)));
                            } else if(datalist3.get(1).equals("3")){
                                userPlayer.setScore(Integer.parseInt(datalist3.get(7)));
                                player1.setScore(Integer.parseInt(datalist3.get(3)));
                                player2.setScore(Integer.parseInt(datalist3.get(5)));
                            }
                            //显示牛数
                            showEnd();
                            //结算输赢
                            try {
                                win();
                            } catch (SQLException ex) {
                                throw new RuntimeException(ex);
                            }
                            reset.setVisible(true);
                        });
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }
    //显示最后各玩家的结果
    private void showEnd() {
        for(Poker poker:playerPoker1){
            poker.turnFront();
        }
        for(Poker poker:playerPoker2){
            poker.turnFront();
        }

        System.out.println("ShowEnd");
        // 获取各玩家分数
        int userScore = userPlayer.getScore();
        int computer1Score = player1.getScore();
        int computer2Score = player2.getScore();

        // 处理分数
        userScore = (userScore > 10 && userScore % 10 != 0) ? userScore % 10 : userScore;
        computer1Score = (computer1Score > 10 && computer1Score % 10 != 0) ? computer1Score % 10 : computer1Score;
        computer2Score = (computer2Score > 10 && computer2Score % 10 != 0) ? computer2Score % 10 : computer2Score;
        if(userScore == 20){
            userScore = 10;
        }
        if(computer1Score == 20){
            computer1Score = 10;
        }
        if(computer2Score == 20){
            computer2Score = 10;
        }

        String str = "file:src/image/game/牛"+ userScore +".png";
        Image image = new Image("file:src/image/game/牛"+userScore +".png");
        ImageView imageView_player = new ImageView(image);
        imageView_player.setFitWidth(340);
        imageView_player.setFitHeight(200);
        imageView_player.setX(190);
        imageView_player.setY(420);
        root.getChildren().add(imageView_player);
        System.out.println(str);

        str = "file:src/image/game/牛"+ computer1Score +".png";
        image = new Image("file:src/image/game/牛"+ computer1Score +".png");
        ImageView imageView_computer1 = new ImageView(image);
        imageView_computer1.setFitWidth(340);
        imageView_computer1.setFitHeight(200);
        imageView_computer1.setX(0);
        imageView_computer1.setY(200);
        root.getChildren().add(imageView_computer1);
        System.out.println(str);

        str = "file:src/image/game/牛"+ computer2Score +".png";
        image = new Image("file:src/image/game/牛"+ computer2Score +".png");
        ImageView imageView_computer2 = new ImageView(image);
        imageView_computer2.setFitWidth(340);
        imageView_computer2.setFitHeight(200);
        imageView_computer2.setX(470);
        imageView_computer2.setY(200);
        root.getChildren().add(imageView_computer2);
        System.out.println(str);

    }
    //玩家点击没牛
    private void noCow() throws SQLException {
        PokerController.autoCalculateBestScore(userPlayer, userPlayerPoker);
        if(userPlayer.getScore() == 0){
            showAlert(Alert.AlertType.INFORMATION, "消息", null, "提交成功！");
            userPlayer.sendDataToServer("score#"+userPlayer.playerID+"#"+userPlayer.getScore()+ "$");
//            //自动计算电脑最佳得分
//            autoCalculate();
//            //显示牛数
//            showEnd();
//            //结算输赢
//            win();
//            reset.setVisible(true);
        }
        else {
            showAlert(Alert.AlertType.INFORMATION, "消息", null, "请认真计算，重新选择！");
        }
    }
    //自动计算电脑最佳得分
    private void autoCalculate() {
        PokerController.autoCalculateBestScore(player1, playerPoker1);
        PokerController.autoCalculateBestScore(player2, playerPoker2);
        for(Poker poker:playerPoker1){
            poker.turnFront();
        }
        for(Poker poker:playerPoker2){
            poker.turnFront();
        }
    }
    //结算输赢
    private void win() throws SQLException {
        // 隐藏
        selectLabel.setVisible(false);
        select.setVisible(false);
        no.setVisible(false);
        // 获取各玩家分数
        int userScore = userPlayer.getScore();
        int computer1Score = player1.getScore();
        int computer2Score = player2.getScore();

        // 处理分数
        userScore = (userScore > 10 && userScore % 10 != 0) ? userScore % 10 : userScore;
        computer1Score = (computer1Score > 10 && computer1Score % 10 != 0) ? computer1Score % 10 : computer1Score;
        computer2Score = (computer2Score > 10 && computer2Score % 10 != 0) ? computer2Score % 10 : computer2Score;

        System.out.println("userScore:" + userScore + "\ncomputer1Score:" + computer1Score + "\ncomputer2Score:" + computer2Score);

        // 判断是否有牛
        boolean userHasNiu = userScore > 0;
        boolean computer1HasNiu = computer1Score > 0;
        boolean computer2HasNiu = computer2Score > 0;

        int userHappyDou = 0; // 用户获得的欢乐豆数量
        String resultMessage;

        if (!userHasNiu && !computer1HasNiu && !computer2HasNiu) { // 三个玩家都没牛
            userHappyDou = happyDou / 3;
            resultMessage = String.format("平局，你得到%d欢乐豆！\n", userHappyDou);
        }
        //两个玩家没牛
        else if ((!computer2HasNiu && !computer1HasNiu) || (!userHasNiu && !computer1HasNiu)||(!computer2HasNiu && !userHasNiu)) {
            if (userHasNiu) {
                userHappyDou = happyDou;
                //数据库经验和欢乐豆更新
                user.setExp(user.getExp()+3);
                user.setHappyDou(user.getHappyDou()+userHappyDou);
                Connection connection= JDBC.getConnection();
                Statement statement=connection.createStatement();
                String sql = "UPDATE user SET exp = '" + user.getExp()+ "' WHERE username = '" + user.getUsername() + "'";
                statement.executeUpdate(sql);
                String sql1="UPDATE user SET happyDou ='"+user.getHappyDou()+"'WHERE username = '"+ user.getUsername() + "'";
                statement.executeUpdate(sql1);
                resultMessage = String.format("恭喜你获得第一名，并且只有你有牛，获得所有欢乐豆%d个！\n", userHappyDou);
            }
            else {
                resultMessage = "很遗憾你输了，没有获得欢乐豆！\n";
            }
        }
        //一个没牛或都有牛
        else {
            //将分数存入数组
            int[] scores = {userScore, computer1Score, computer2Score};
            //排序数组，升序
            Arrays.sort(scores);
            int maxScore = scores[2];//最大值
            int secondScore = scores[1];//第二值
            //玩家是否为第一或第二
            boolean userIsFirst = userScore == maxScore;
            boolean userIsSecond = userScore == secondScore;
            //电脑1是否为第一或第二
            boolean computer1IsFirst = computer1Score == maxScore;
            boolean computer1IsSecond = computer1Score == secondScore;
            //电脑2是否为第一或第二
            boolean computer2IsFirst = computer2Score == maxScore;
            boolean computer2IsSecond = computer2Score == secondScore;
            //计算第一第二的欢乐豆
            int firstPlaceHappyDou = (int) (happyDou * 0.65);
            int secondPlaceHappyDou = (int) (happyDou * 0.35);

            if (userIsFirst) {
                userHappyDou = firstPlaceHappyDou;
                resultMessage = String.format("恭喜你获得第一名，获得%d欢乐豆！\n", userHappyDou);
            } else if (userIsSecond) {
                userHappyDou = secondPlaceHappyDou;
                resultMessage = String.format("你获得第二名，获得%d欢乐豆！\n", userHappyDou);
            } else {
                resultMessage = "很遗憾你输了，没有获得欢乐豆！\n";
            }

            // 如果有多个玩家得分相同，比较花色数量
            if ((userIsFirst && computer1IsFirst) || (userIsFirst && computer2IsFirst) || (computer1IsFirst && computer2IsFirst)) {
                int userSuitRank = PokerController.getSuitRank(userPlayerPoker);
                int computer1SuitRank = PokerController.getSuitRank(playerPoker1);
                int computer2SuitRank = PokerController.getSuitRank(playerPoker2);
                //第一，二相同
                if (userIsFirst) {
                    if (computer1IsFirst && userSuitRank < computer1SuitRank) {
                        userHappyDou = secondPlaceHappyDou;
                        resultMessage = String.format("你获得第二名，获得%d欢乐豆！\n", userHappyDou);
                    } else if (computer2IsFirst && userSuitRank < computer2SuitRank) {
                        userHappyDou = secondPlaceHappyDou;
                        resultMessage = String.format("你获得第二名，获得%d欢乐豆！\n", userHappyDou);
                    } else {
                        userHappyDou = firstPlaceHappyDou;
                        resultMessage = String.format("你获得第一名，获得%d欢乐豆！\n", userHappyDou);
                    }
                }
                //第二，三相同
                if (userIsSecond) {
                    if (computer1IsSecond && userSuitRank < computer1SuitRank) {
                        resultMessage = "很遗憾你输了，没有获得欢乐豆！\n";
                    } else if (computer2IsSecond && userSuitRank < computer2SuitRank) {
                        resultMessage = "很遗憾你输了，没有获得欢乐豆！";
                    }
                }
            }
        }
        // 显示结果
        showAlert(Alert.AlertType.INFORMATION, "消息", null, resultMessage);

    }
    //点击重置游戏
    private void resetGame() {

    }
    //弹出警告
    private void showAlert(Alert.AlertType alertType, String title, String headerText, String contentText) {
        Alert alert = new Alert(alertType);
        alert.setTitle(title);
        alert.setHeaderText(headerText);
        alert.setContentText(contentText);
        alert.showAndWait();
    }
}
